import 'dart:async';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'map_common_config.dart';
import 'map_location_controller.dart';
import 'package:get/get.dart';
import 'dart:io';

class MapLocationView extends StatefulWidget {
  List<Marker>? marks = [];
  Function? locationBlock;


  MapLocationView({Key? key, this.marks, this.locationBlock,}) : super(key: key);

  @override
  State<MapLocationView> createState() => _MapLocationViewState();
}

class _MapLocationViewState extends State<MapLocationView> {
  AMapController? mapController;
  LatLng? latLng;
  CameraPosition? kInitialPosition;
  MapLocationController mapLocationController =
      Get.put(MapLocationController());
  late Map<String, Object> _locationResult;

  late StreamSubscription<Map<String, Object>> _locationListener;

  AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  @override
  Widget build(BuildContext context) {
    return getMapView();
  }

  Widget getMapView() {
    return GetBuilder(
        id: mapLocationController.mapViewId,
        builder: (MapLocationController controller) {
          return AMapWidget(
            initialCameraPosition: kInitialPosition!,
            privacyStatement: MapCommonConfig.mapPrivacyStatement,
            apiKey: MapCommonConfig.mapApiKeys,
            onMapCreated: onMapCreated,
           // onLocationChanged: _onLocationChanged,
            myLocationStyleOptions: MyLocationStyleOptions(
              true,
              circleFillColor: Colors.lightBlue,
              circleStrokeColor: Colors.blue,
              circleStrokeWidth: 1,
            ),
            markers: Set<Marker>.of(widget.marks ?? []),
          );
        });
  }

  void onMapCreated(AMapController controller) {
    mapController = controller;
    mapController?.getMapContentApprovalNumber();
    getCurrentLocation();
    // mapLocationController.update([mapLocationController.mapViewId]);
  }

  void _onLocationChanged(AMapLocation location) {
    if (null == location) {
      return;
    }
    print('_onLocationChanged ${location.toJson()}');
    List latList = location.toJson()['latlng'];
    if (latList.first > 0 && mapLocationController.isGetLocations == false) {
      mapLocationController.isGetLocations == true;
      double latitude = latList.first;
      double longitude = latList.last;
      changeCenterPosition(latitude, longitude);
      // if (widget.locationBlock != null) {
      //   widget.locationBlock!(location.toJson());
      // }
    }
  }

  void changeCenterPosition(double latitude, double longitude) {
    if(mapController!=null){
      mapController?.moveCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(
            //中心点
              target: LatLng(latitude, longitude),
              //缩放级别
              zoom: 14,
              //俯仰角0°~45°（垂直与地图时为0）
              tilt: 30,
              //偏航角 0~360° (正北方为0)
              bearing: 0),
        ),
        animated: true,
      );
      mapLocationController.update([mapLocationController.mapViewId]);
    }

  }

  void getCurrentLocation() async {
    /// [hasShow] 隐私权政策是否弹窗展示告知用户
    AMapFlutterLocation.updatePrivacyShow(true, true);

    /// [hasAgree] 隐私权政策是否已经取得用户同意
    AMapFlutterLocation.updatePrivacyAgree(true);

    /// 动态申请定位权限
    requestPermission();
    AMapFlutterLocation.setApiKey(
        MapCommonConfig.androidKey, MapCommonConfig.iosMapKey);

    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    _startLocation();

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      print('定位结果：$result');
      mapLocationController.isGetLocations = true;
      _locationResult = result;
      double latitude=0.0;
      double longitude=0.0;
      if(result['latitude']!=null){
         latitude = double.parse(result['latitude'].toString());
         longitude = double.parse(result['longitude'].toString());
        changeCenterPosition(latitude, longitude);
      }
      if (widget.locationBlock != null) {
        widget.locationBlock!(latitude, longitude,result);
      }
    });
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }

  ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      ///开始定位之前设置定位参数
      _setLocationOption();
      _locationPlugin.startLocation();
    }
  }

  ///设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption =  AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = true;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;

      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 2000;

      ///设置Android端的定位模式<br>
      ///可选值：<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      /// 可选值：<br>
      /// <li>[DesiredAccuracy.Best] 最高精度</li>
      /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
      /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
      /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
      /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
      locationOption.desiredAccuracy = DesiredAccuracy.HundredMeters;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);
    }
  }

  @override
  void initState() {
    super.initState();
    kInitialPosition =
        const CameraPosition(target: LatLng(39.909187, 116.397451), zoom: 10);
  }

  @override
  void dispose() {
    super.dispose();
    ///移除定位监听
    if (null != _locationListener) {
      _locationListener.cancel();
    }

    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }
  }
}
